package com.rd.p2p.app.borrow;

import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.service.BaseGiveAwardService;
import com.qdlc.p2p.biz.service.CollectPayService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.service.UserWineCouponsService;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.BorrowStatus;
import com.qdlc.p2p.common.constant.UserWineCouponsStatus;
import com.qdlc.p2p.common.constant.WineCouponsType;
import com.qdlc.p2p.common.constant.WineCouponsUseType;
import com.qdlc.p2p.common.core.ReturnResult;
import com.qdlc.p2p.common.enums.EnumWineCouponsIdsType;
import com.qdlc.p2p.common.exception.WineCouponsException;
import com.qdlc.p2p.common.util.MessageUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.dao.AdditionalCommodityDao;
import com.qdlc.p2p.dal.dao.BorrowDao;
import com.qdlc.p2p.dal.dao.UserWineCouponsDao;
import com.qdlc.p2p.dal.dto.*;
import com.qdlc.p2p.dal.model.BaseGiveAwardModel;
import com.qdlc.p2p.dal.model.UserWineCouponsModel;
import com.qdlc.p2p.dal.util.UserUtils;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.factory.annotation.Qualifier;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by 51ky on 2016/8/11.
 */
public class AppWinCouponsAction extends BaseAction<UserWineCouponsModel> implements ModelDriven<UserWineCouponsModel> {

    @Resource
    private UserWineCouponsDao userWineCouponsDao;

    @Resource
    private UserIdentifyService userIdentifyService;

    @Resource
    @Qualifier("wineCouponsCollectService")
    private CollectPayService collectService;

    @Resource
    private BorrowDao borrowDao;

    @Resource
    private UserWineCouponsService userWineCouponsService;

    @Resource
    private AdditionalCommodityDao additionalCommodityDao;

    @Resource
    @Qualifier("giveUserCommodityService")
    private BaseGiveAwardService giveUserCommodityService;

    /**
     * 我的酒券数据
     *
     * @throws IOException
     */
    @Action("/app/member/redpacket/availableWineCouponsJSON")
    public void availableWineCouponsJSON() throws IOException {
        User user = getSessionUser();
        Map<String,Object> data = new HashMap<String, Object>();
        if(user == null){
            printWebResCodeAndMsgResult("-1","用户尚未登陆!");
            return;
        }
        model.setUserId(getSessionUserId());
        List<UserWineCouponsModel> allList = userWineCouponsDao.getAllList(model);
        data.put("data", allList);
        printWebJson(getStringOfJpaObj(data));
    }

    /**
     * PS 现金酒券兑换现金
     *
     * @throws Exception
     */
    @Action("/app/member/redpacket/wineCouponsExchange")
    public void wineCouponsExchange() throws Exception {
        User toUser = getSessionUser();
        if(toUser == null){
            printWebResCodeAndMsgResult("-1","用户尚未登陆!");
            return;
        }
        UserIdentify ui = userIdentifyService.getUserIdentifyByUserId(toUser.getUserId());
        String tppUserCustId = UserUtils.getUserTppCustId(toUser.getUserId());
        if (ui.getRealNameStatus() != 1 || StringUtil.isBlank(tppUserCustId)) {
            printWebResCodeAndMsgResult("0","您还未开通第三方账户，请先开户！");
            return;
        }
        long[] wineCouponsIds = model.getWineCouponsIds();
        if (StringUtil.isBlank(wineCouponsIds)) {
            printWebResCodeAndMsgResult("0","酒券选择有误，请重新选择！");
            return;
        }

        // 还款后才能使用
        List<Long> ids = getWineCouponsIdList(wineCouponsIds);// 酒券ids
        List<UserWineCoupons> userWineCouponsList = userWineCouponsDao.getWineCouponsByIds(ids);// 酒券List
        // 酒券校验
        for (UserWineCoupons userWineCoupons : userWineCouponsList) {// 不是投标所获的酒券不能兑现
            if (userWineCoupons.getVersion() == 0) {
                printWebResCodeAndMsgResult("0","您的选择存在非投标所获的酒券，请重新选择！");
                return;
            }
            // 防止非法篡改
            if (userWineCoupons.getUserId() != toUser.getUserId()) {
                printWebResCodeAndMsgResult("0","所选酒券存在错误，请重新选择！");
                return;
            }
        }
        List<Long> borrowIds = getBorrowIdList(userWineCouponsList);// borrowIds
        List<Borrow> borrow = borrowDao.getBorrowByStatusAndIds(BorrowStatus.STATUS_REPAYMENT_DONE, borrowIds);
        if (borrow.size() > 0) {
            printWebResCodeAndMsgResult("0","所选酒券存在错误，请重新选择！");
            return;
        }

        // 请求兑现
        for (long wineCouponsId : wineCouponsIds) {
            long[] wcIds = {wineCouponsId};
            cashWineCouponsExchange(wcIds, toUser.getUserId());
        }
        printWebResCodeAndMsgResult("1","兑换成功");
    }

    /**
     * 把酒券的long数据转成酒券list
     *
     * @param wineCouponsIds 酒券IDS
     */
    private List<Long> getWineCouponsIdList(long[] wineCouponsIds) {
        List<Long> ids = new ArrayList<Long>(wineCouponsIds.length);
        for (long wineCouponsId : wineCouponsIds) {
            ids.add(wineCouponsId);
        }
        return ids;
    }

    /**
     * 把酒券list数据转成酒券List<Long>（关联的标id）
     *
     * @param wineCouponsList 酒券List
     */
    private List<Long> getBorrowIdList(List<UserWineCoupons> wineCouponsList) {
        List<Long> ids = new ArrayList<Long>(wineCouponsList.size());
        for (UserWineCoupons wineCoupon : wineCouponsList) {
            long borrowId = wineCoupon.getVersion();// 关联的标id
            ids.add(borrowId);
        }
        return ids;
    }

    /**
     * 现金酒券兑现
     */
    private void cashWineCouponsExchange(long[] wineCouponsIds, long exchangeUserId) {
        TppTradeLog tppTradeLog = collectService.createOrder(wineCouponsIds, exchangeUserId, WineCouponsType.CASH, WineCouponsUseType.EXCHANGE_AMOUNT);
        ReturnResult returnResult = collectService.requestOrder(tppTradeLog);
        if (returnResult.isError()) {
            throw new WineCouponsException("酒券兑现失败!", WineCouponsException.TYPE_JSON);
        }
    }

    /**
     * PS 现金酒券兑换酒
     *
     * @throws Exception
     */
    @Action("/app/member/redpacket/wineExchange")
    public void wineExchange() throws Exception {
        User toUser = getSessionUser();
        if(toUser == null){
            printWebResCodeAndMsgResult("-1","用户尚未登陆!");
            return;
        }
        UserIdentify ui = userIdentifyService.getUserIdentifyByUserId(toUser.getUserId());
        String tppUserCustId = UserUtils.getUserTppCustId(toUser.getUserId());
        if (ui.getRealNameStatus() != 1 || StringUtil.isBlank(tppUserCustId)) {
            printWebResCodeAndMsgResult("0","您还未开通第三方账户，请先开户！");
            return;
        }
        if (StringUtil.isBlank(model.getWineCouponsIds())) {
            printWebResCodeAndMsgResult("0","请先选择酒券");
            return;
        }
        if (model.getWineCouponsIds().length % 6 != 0) {
            printWebResCodeAndMsgResult("0","请选择6或6的倍数的酒卡！");
            return;
        }
        cashwineExchange(model.getWineCouponsIds(), toUser);
        printWebResCodeAndMsgResult("1","兑换成功！");
    }


    /**
     * 现金酒券兑现
     */
    private void cashwineExchange(long[] wineCouponsIds, User exchangeUser) throws IOException {
        // 发放商品
        int length = wineCouponsIds.length / 6;
        for (int i = 0; i < length; i++) {// 6张酒券兑换一箱酒
            long wineCouponsId = wineCouponsIds[0];// 默认取第一条
            QueryParam queryParam = QueryParam.getInstance();
            queryParam.addParam("id", wineCouponsId);
            List<UserWineCoupons> wineCouponsList = userWineCouponsDao.findByCriteria(queryParam);
            UserWineCoupons wineCoupons = wineCouponsList.get(0);
            BaseGiveAwardModel baseGiveAwardModel = new BaseGiveAwardModel(exchangeUser, wineCoupons.getAmount(), EnumWineCouponsIdsType.WINE_EXCHANGE.getValue(), 0, "酒券兑换");
            // 获取商品id
            QueryParam queryParam2 = QueryParam.getInstance();
            queryParam2.addParam("category", wineCoupons.getKeyId());
            AdditionalCommodity additionalCommodity = additionalCommodityDao.findByCriteria(queryParam2).get(0);
            if (StringUtil.isBlank(additionalCommodity)) {
                printWebResCodeAndMsgResult("0","酒已售罄！");
                return;
            }
            baseGiveAwardModel.setRuleId(additionalCommodity.getId());
            giveUserCommodityService.giveSingleUserAward(baseGiveAwardModel);
        }

        // 酒券更新为已使用
        for (int i = 0; i < wineCouponsIds.length; i++) {
            long userWineCouponsId = wineCouponsIds[i];
            userWineCouponsService.updateStatus(userWineCouponsId, UserWineCouponsStatus.USE, UserWineCouponsStatus.NO_USE);
        }
    }
}
